package com.zb.framework.wechatnews.service.impl;

import com.zb.framework.wechatnews.common.BizException;
import com.zb.framework.wechatnews.common.EnumsError;
import com.zb.framework.wechatnews.entity.AccessToken;
import com.zb.framework.wechatnews.entity.UpdateTaskCard;
import com.zb.framework.wechatnews.entity.BaseMessage;
import com.zb.framework.wechatnews.entity.WeChatResult;
import com.zb.framework.wechatnews.service.SendMessageService;
import com.zb.framework.wechatnews.utils.JsonUtil;
import com.zb.framework.wechatnews.utils.WeChatUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Auther: 周作为
 * @Date: 2019/6/18 14:32
 * @Description:
 */
@Service
public class SendMessageServiceImpl implements SendMessageService {

    private static Logger log = LoggerFactory.getLogger(SendMessageServiceImpl.class);

    @Value("${enterprise.wechat.corpId}")
    private String CORPID;  //凭证

    @Value("${enterprise.wechat.corpsecret}")
    private String CORPSECRET; //密钥

    //发送消息请求url,请求方式：POST（HTTPS）
    private static final String SENDMESSAGE_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";

    //更新用户任务卡片消息的选择状态。 请求方式：POST（HTTPS）
    private static final String UPDATE_TASK_CARD_URL = " https://qyapi.weixin.qq.com/cgi-bin/message/update_taskcard?access_token=";


    /**
     * 发送消息
     * @param accessToken
     * @param message
     * @return
     */
    @Override
    public WeChatResult sendMessage(String accessToken, String message) {

        log.info("请求发送消息的message:" + message);
        //2.获取请求的url
        String sendMessageUrl = SENDMESSAGE_URL + accessToken;
        //3.调用接口，发送消息
        JSONObject jsonObject = WeChatUtil.httpRequest(sendMessageUrl, "POST", message);
        log.info("发送消息的返回jsonObject:" + jsonObject);

        //4. 错误处理
        if (null != jsonObject) {
            int errcode = jsonObject.getInt("errcode");
            if (0 == errcode) {
                //批量发送推送消息时，可能存在部分用户发送消息成功，部分用户userid不合法的情况
                if (!"".equals(jsonObject.getString("invaliduser"))) {
                    log.warn("发送企业微信成功，部分用户userId不合法，不合法的userId = " + jsonObject.getString("invaliduser"));
                } else {
                    log.info("发送企业微信消息成功" + message);
                }
            } else {
                //如果是由于token失效,则替换老的token，重新调用
                //企业微信全局错误码参考 https://work.weixin.qq.com/api/doc#90000/90139/90313
                //42001 access_token已过期
                if (42001 == errcode) {
                    String key = CORPID + "_" + CORPSECRET;
                    //重新获取token之前,首先删除过期的token
                    WeChatUtil.tokenMap.remove(key);
                    //再重新获取新token
                    AccessToken newToken = WeChatUtil.getAccessToken(CORPID,CORPSECRET);
                    //重新发送消息
                    sendMessage(newToken.getToken(), message);
                    //替换过期的token，所以先锁tokenMap不让别人用
                    synchronized (WeChatUtil.tokenMap) {
                        //替换新的token
                        WeChatUtil.tokenMap.put(key, newToken);
                    }
                } else {
                    log.error("发送企业微信消息失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
                    throw new BizException(jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
                }
            }
        }else {
            log.info("请求发送企业微信消息返回为空，requestUrl =" + sendMessageUrl);
            throw new BizException(EnumsError.SENDMESSAGE_FAILED);
        }
        WeChatResult weChatResult = (WeChatResult) JSONObject.toBean(jsonObject,WeChatResult.class);
        return weChatResult;
    }


    /**
     * 更新任务卡片按钮状态
     * @param accessToken
     * @param record
     * @return
     */
    @Override
    public WeChatResult updateTaskCard(String accessToken, UpdateTaskCard record) {
        //1.获取json字符串：将record对象转换为json字符串
        String jsonMessage = JsonUtil.obj2String(record);  //将record对象转换为json字符串
        log.info("请求发送消息的jsonTextMessage:" + jsonMessage);
        //2.获取请求的url
        String sendMessageUrl = UPDATE_TASK_CARD_URL + accessToken;
        //3.调用接口，发送消息
        JSONObject jsonObject = WeChatUtil.httpRequest(sendMessageUrl, "POST", jsonMessage);
        if(null != jsonObject){
            int errcode = jsonObject.getInt("errcode");
            if(0 == errcode){
                log.info("任务卡片按钮状态更新成功" + jsonMessage);
            }else {
                throw new BizException(jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }else {
            throw new BizException(EnumsError.UPDATE_TASK_CARD);
        }
        WeChatResult weChatResult = (WeChatResult) JSONObject.toBean(jsonObject,WeChatResult.class);
        return weChatResult;
    }
}
